﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Xml.Linq;
using System.Web.Services;
using Telerik.Web.UI;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.MODEL;

namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class BGM_Project_Option_Old : System.Web.UI.Page
    {
        private IProject projectBLL;
        private string type;

        protected void Page_Load(object sender, EventArgs e)
        {
            type = Request.QueryString["type"].ToString();

            if (type.Length > 0)
            {
                projectBLL = Project_Factory.GetProjectFactory(type);
            }

            if (!IsPostBack)
            {
                
                lbOptionType.Text = Request.QueryString["optType"].ToString();
                //gridOption.Columns[0].HeaderText = Request.QueryString["optName"].ToString();

                string optName = Request.QueryString["optName"].ToString();
                if (optName == "prd")
                    gridOption.Columns[0].HeaderText = "สินค้า/บริการ";
                else if (optName == "mar")
                    gridOption.Columns[0].HeaderText = "ตลาด(ภูมิภาค/ประเทศ";
                else if (optName == "prj")
                    gridOption.Columns[0].HeaderText = "โครงการบูรณาการ";
                else
                    RadAjaxManager1.Alert("ตรวจสอบ optName!!");


                if (!Object.Equals(Session["ProjectID"], null))
                {
                    lbProjectID.Text = Session["ProjectID"].ToString();
                }

                if (!Object.Equals(Session["ProjectName"], null))
                {
                    litTitle.Text = Session["ProjectName"].ToString();
                }

                LoadData();
            }
        }

        private void LoadData()
        {
            //if (ViewState["DataOption"] == null)
            //{
                DataTable dtb = projectBLL.ListProjectOptionGrid(lbProjectID.Text, lbOptionType.Text);
                gridOption.DataSource = dtb;
            //    ViewState["DataOption"] = dtb;
            //}
            //else
            //{
            //    gridOption.DataSource = (DataTable)ViewState["DataOption"];
            //}

            gridOption.DataBind();
        }

        protected void btnSaveAddNewOpt_Click(object sender, EventArgs e)
        {
            double db = 0;
            int count = 0;
            Label lbOptSeq = null, lbProjOptSeq = null;
            string[] optSeq = new string[gridOption.Items.Count];
            string[] projOptSeq = new string[gridOption.Items.Count];
            string[] weight = new string[gridOption.Items.Count];
            for (int i = 0; i < gridOption.Items.Count; i++)
            {
                lbOptSeq = (Label)gridOption.MasterTableView.Items[i].FindControl("lbOptSeq");
                lbProjOptSeq = (Label)gridOption.MasterTableView.Items[i].FindControl("lbProjOptSeq");
                RadNumericTextBox txt = (RadNumericTextBox)gridOption.MasterTableView.Items[i].FindControl("txtWeight");

                if (txt.Text.Length > 0 || lbProjOptSeq.Text.Length > 0)
                {
                    db += (txt.Text.Length > 0) ? Convert.ToDouble(txt.Text) : 0;
                    optSeq[count] = lbOptSeq.Text;
                    projOptSeq[count] = lbProjOptSeq.Text;
                    weight[count] = txt.Text;

                    count++;
                }
            }

            if (db == 100)
            {
                try
                {
                    for (int i = 0; i < count; i++)
                    {
                        if (!Object.Equals(projOptSeq[i], ""))
                        {
                            if (!Object.Equals(weight[i], ""))
                            {
                                projectBLL.UpdateProjectOption(projOptSeq[i], "", Convert.ToDouble(weight[i]), optSeq[i], new SsMng().GetUss(SsMng.SsUserType.EmpSeq));
                            }
                            else
                            {
                                projectBLL.DeleteProjectOption(projOptSeq[i]);
                            }
                        }
                        else
                        {
                            if (!Object.Equals(weight[i], ""))
                            {
                                projectBLL.InsertProjectOption(lbProjectID.Text, "", Convert.ToDouble(weight[i]), optSeq[i], new SsMng().GetUss(SsMng.SsUserType.EmpSeq));
                            }
                        }
                    }
                    RadAjaxManager1.Alert("บันทึกข้อมูลเรียบร้อย");
                    RadAjaxManager1.ResponseScripts.Add("returnToParent();");
                    //LoadData();                    
                }
                catch
                {
                    RadAjaxManager1.Alert("เกิดข้อผิดพลาดในการบันทึก");
                }
            }
            else if(db == 0)
            {
                bool sta = false;
                try
                {
                    for (int i = 0; i < count; i++)
                    {
                        if (!Object.Equals(projOptSeq[i], ""))
                        {
                            projectBLL.DeleteProjectOption(projOptSeq[i]);
                            sta = true;
                        }
                    }
                    if (sta)
                    {
                        RadAjaxManager1.Alert("บันทึกข้อมูลเรียบร้อย");
                    }
                    RadAjaxManager1.ResponseScripts.Add("returnToParent();");
                }
                catch(Exception ex)
                {
                    RadAjaxManager1.Alert(ex.Message);
                }
            }
            else
            {
                RadAjaxManager1.Alert("น้ำหนักรวมทั้งหมดต้องเท่ากับ 100%");
            }
        }

        protected void gridOption_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Filter")
            {
                //if (ViewState["DataOption"] != null)
                //{
                //    DataTable dtb = (DataTable)ViewState["DataOption"];
                    
                //    for (int i = 0; i < dtb.Rows.Count; i++)
                //    {
                //        string strWeight = ((RadNumericTextBox)gridOption.Items[i]["Weight"].FindControl("txtWeight")).Text;

                //        if (strWeight.Length == 0)
                //        {
                //            dtb.Rows[i]["weight"] = DBNull.Value;
                //        }
                //        else
                //        {
                //            dtb.Rows[i]["weight"] = strWeight;
                //        }
                //    }
                //}
                
                LoadData();
            }
        }

        int sum = 0;
        protected void gridOption_ItemDataBound(object sender, GridItemEventArgs e)
        {
            //if (e.Item is GridDataItem)
            //{
                //GridDataItem dataItem = (GridDataItem)e.Item;
                //RadNumericTextBox txtWeight = (RadNumericTextBox)dataItem["Weight"].FindControl("txtWeight");

                //txtWeight.Attributes.Add("OnBlur", string.Format("txtBlur('{0}')"
                //    , txtWeight.ClientID));
                //txtWeight.Attributes.Add("OnFocus", string.Format("txtFocus('{0}')"
                //    , txtWeight.ClientID));

                //if ((bool)Session["Approve"])
                //{
                //    txtWeight.ReadOnly = true;
                //}
            //}
            if (e.Item is GridDataItem)
            {
                GridDataItem dataItem = (GridDataItem)e.Item;
                string strTmp = (dataItem["Weight"].FindControl("txtWeight") as RadNumericTextBox).Value.ToString();
                if(strTmp.Length>0)
                    sum += int.Parse(strTmp);
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                (footer["Weight"].FindControl("txtFooterWeight") as RadNumericTextBox).Value = int.Parse(sum.ToString());
            }
        }

        protected void cbNotFix_CheckedChanged(object sender, EventArgs e)
        {
            gridOption.Enabled = !cbNotFix.Checked;
            //for (int i = 0; i < gridOption.Items.Count; i++)
            //{
            //    (gridOption.Items[i]["Weight"].FindControl("txtFooterWeight") as RadNumericTextBox).Text = "";
            //}
            //foreach (DataRow dr in gridOption.Items)
            //{ 
            //    dr["Weight"].
            //}
        }
    }
}
